package com.smfx.yxt.baidu.aip;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.face.AipFace;
import com.smfx.yxt.baidu.model.AipFaceDetect;
import com.smfx.yxt.baidu.model.FaceInfo;
import com.smfx.yxt.utils.JsonUtils;;

public class AipFaceClient {
	
	static Logger logger = LoggerFactory.getLogger(AipFaceClient.class);

	//设置APPID/AK/SK
    private static final String APP_ID = "15770924";
    private static final String API_KEY = "33EOYvBIlZGl7PEHkPg0K7RY";
    private static final String SECRET_KEY = "qaGYaC802pggQntzltmMhXcUE8Iu8tMV";
    
    public static AipFace init() {
    	// 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        return client;
    }
	
    /**
     * 人脸检测
     * @param client
     */
	public static AipFaceDetect apiFaceDetect(String image, 
			String imageType) throws Exception{
		AipFace client = init();
		//传入可选参数调用接口
	    HashMap<String, String> options = new HashMap<String, String>();
	    options.put("face_field", "age,beauty,expression,gender,glasses");
	    options.put("max_face_num", "10");
	    options.put("face_type", "LIVE");
	    
	    // 人脸检测
	    JSONObject res = client.detect(image, imageType, options);
	    logger.info("--人脸检测 result={}", res.toString());
	    AipFaceDetect faceDetect = JsonUtils.jsonToObject(res.toString(), AipFaceDetect.class);
	    if(faceDetect.getError_code().equals("0")) {
          	if(faceDetect.getResult().getFace_list().size() > 1) {
          		faceDetect.setError_code(ErrorCode.FACE_NUM_OUT.getErrorCode());
          		faceDetect.setError_msg(ErrorCode.FACE_NUM_OUT.getErrorMsg());
  			}else {
  				FaceInfo faceInfo = faceDetect.getResult().getFace_list().get(0);
  				if(faceInfo.getGlasses().isGlasses()) {
  					faceDetect.setError_code(ErrorCode.HAS_GLASSES.getErrorCode());
  	          		faceDetect.setError_msg(ErrorCode.HAS_GLASSES.getErrorMsg());
  	          		return faceDetect;
  				}
  				if(faceInfo.getLocation().getHeight() < 250 || faceInfo.getLocation().getWidth() < 260) {
  					faceDetect.setError_code(ErrorCode.FACE_SIZE_MIN.getErrorCode());
  	          		faceDetect.setError_msg(ErrorCode.FACE_SIZE_MIN.getErrorMsg());
  	          		return faceDetect;
  				}
  			}
		}else {
			faceDetect.setError_msg(ErrorCode.getErrorDesc(faceDetect.getError_code()));
		}
	    return faceDetect;
	}
	
	/**
	 * 在线图片转换成base64字符串
	 * @param imgURL	图片线上路径
	 * @return
	 */
	public static String ImageToBase64ByOnline(String imgURL) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();		
		try {
    		File file = new File(imgURL);
			InputStream is = new FileInputStream(file);
			// 创建URL			
			byte[] by = new byte[1024];			
			// 将内容读取内存中			
			int len = -1;			
			while ((len = is.read(by)) != -1) {				
				data.write(by, 0, len);			
			}			
			// 关闭流			
			is.close();		
		} catch (IOException e) {			
			e.printStackTrace();		
		}		
		// 对字节数组Base64编码	
		return Base64.encodeBase64String(data.toByteArray());
	}
}
